package com.bkgy.modular.hotcoldedgeanalyse.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bkgy.excelhandle.PlanExcelHandlerImpl;
import com.bkgy.modular.datacollect_bx.bean.JDataSave621;
import com.bkgy.modular.hotcoldedgeanalyse.dao.ColdEdgeSameDao;
import com.bkgy.modular.hotcoldedgeanalyse.entity.ColdEdgeSame;
import com.bkgy.modular.hotcoldedgeanalyse.entity.ColdStatistics;
import com.bkgy.modular.hotcoldedgeanalyse.entity.ExportColdEdgeSame;
import com.bkgy.sys.common.entity.ResultData;
import com.bkgy.util.ExcelUtilsPOI;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ColdEdgeSameService {

    @Resource
    private ColdEdgeSameDao coldEdgeSameDao;

    @Resource
    private MongoTemplate mongoTemplate;

    public ResultData findDataByPage(JSONObject json) {
        try {
            Integer pageIndex = json.getInteger("pageIndex");
            Integer pageSize = json.getInteger("pageSize");
            if (pageIndex == null || pageSize == null) {
                return ResultData.ResultDataFaultSelf("分页参数没有传", null);
            }
            //查询条件
            String cold_coil_id = null;
            String hot_id = null; // 热卷号
            String dbegin = null;
            String dend = null;
            String ex_thk1 = null;  //产品厚度----开始
            String ex_thk2 = null;  //产品厚度---结束
            String en_wid1 = null;  //原料宽度----开始
            String en_wid2 = null;  //原料宽度----结束
            String en_thk1 = null;  //原料厚度----开始
            String en_thk2 = null;  //原料厚度----结束
            String ele_si1 = null;  //硅含量---开始
            String ele_si2 = null;  //硅含量---结束
            String steelgrade = null;  //钢种
            String shift = null;
            String crew = null;
            JSONObject condition = json.getJSONObject("condition");
            if (!condition.isEmpty()) {
                if (StringUtils.hasText(condition.getString("cold_coil_id"))) {
                    cold_coil_id = condition.getString("cold_coil_id");
                }
                if (StringUtils.hasText(condition.getString("hot_id"))) {
                    hot_id = condition.getString("hot_id");
                }
                if (StringUtils.hasText(condition.getString("dbegin"))) {
                    dbegin = condition.getString("dbegin");
                }
                if (StringUtils.hasText(condition.getString("dend"))) {
                    dend = condition.getString("dend");
                }
                if (StringUtils.hasText(condition.getString("ex_thk1"))) {
                    ex_thk1 = condition.getString("ex_thk1");
                }
                if (StringUtils.hasText(condition.getString("ex_thk2"))) {
                    ex_thk2 = condition.getString("ex_thk2");
                }
                if (StringUtils.hasText(condition.getString("en_wid1"))) {
                    en_wid1 = condition.getString("en_wid1");
                }
                if (StringUtils.hasText(condition.getString("en_wid2"))) {
                    en_wid2 = condition.getString("en_wid2");
                }
                if (StringUtils.hasText(condition.getString("en_thk1"))) {
                    en_thk1 = condition.getString("en_thk1");
                }
                if (StringUtils.hasText(condition.getString("en_thk2"))) {
                    en_thk2 = condition.getString("en_thk2");
                }
                if (StringUtils.hasText(condition.getString("ele_si1"))) {
                    ele_si1 = condition.getString("ele_si1");
                }
                if (StringUtils.hasText(condition.getString("ele_si2"))) {
                    ele_si2 = condition.getString("ele_si2");
                }
                if (StringUtils.hasText(condition.getString("steelgrade"))) {
                    steelgrade = condition.getString("steelgrade");
                }
                if (StringUtils.hasText(condition.getString("shift"))) {
                    shift = condition.getString("shift");
                }
                if (StringUtils.hasText(condition.getString("crew"))) {
                    crew = condition.getString("crew");
                }
            }


            List<ColdEdgeSame> list = coldEdgeSameDao.findDataByPage((pageIndex - 1) * pageSize, pageIndex * pageSize, dbegin, dend, ex_thk1, ex_thk2, en_wid1, en_wid2, en_thk1, en_thk2, ele_si1, ele_si2, steelgrade, shift, crew, cold_coil_id,hot_id);
            Integer count = coldEdgeSameDao.findDataCount(dbegin, dend, ex_thk1, ex_thk2, en_wid1, en_wid2, en_thk1, en_thk2, ele_si1, ele_si2, steelgrade, shift, crew, cold_coil_id,hot_id);

            //统计
            Map<Double, Long> map1 = null;
            Map<Double, Long> map2 = null;
            //边降
            Double edge_a_abs_lenAll = 0.0;
            Double edge_b_abs_lenAll = 0.0;
            Double edge_c_abs_lenAll = 0.0;
            Double edge_d_abs_lenAll = 0.0;
            Double edge_e_abs_lenAll = 0.0;

            edge_a_abs_lenAll = list.stream().filter(x -> !StringUtils.isEmpty(x.getEdge_a_abs_len())).mapToDouble(ColdEdgeSame::getEdge_a_abs_len).sum();
            edge_b_abs_lenAll = list.stream().filter(x -> !StringUtils.isEmpty(x.getEdge_b_abs_len())).mapToDouble(ColdEdgeSame::getEdge_b_abs_len).sum();
            edge_c_abs_lenAll = list.stream().filter(x -> !StringUtils.isEmpty(x.getEdge_c_abs_len())).mapToDouble(ColdEdgeSame::getEdge_c_abs_len).sum();
            edge_d_abs_lenAll = list.stream().filter(x -> !StringUtils.isEmpty(x.getEdge_d_abs_len())).mapToDouble(ColdEdgeSame::getEdge_d_abs_len).sum();
            edge_e_abs_lenAll = list.stream().filter(x -> !StringUtils.isEmpty(x.getEdge_e_abs_len())).mapToDouble(ColdEdgeSame::getEdge_e_abs_len).sum();

            List<Double> s1List = list.stream().map(ColdEdgeSame::getS1_wr_shifting_ave).collect(Collectors.toList());
            List<Double> s2List = list.stream().map(ColdEdgeSame::getS2_wr_shifting_ave).collect(Collectors.toList());
            map1 = s1List.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
            map2 = s2List.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
            //统计赋值
            ColdStatistics coldStatistics = new ColdStatistics();
            coldStatistics.setS1Collect(map1);
            coldStatistics.setS2Collect(map2);

            coldStatistics.setEdge_a_abs_lenAll(edge_a_abs_lenAll);
            coldStatistics.setEdge_b_abs_lenAll(edge_b_abs_lenAll);
            coldStatistics.setEdge_c_abs_lenAll(edge_c_abs_lenAll);
            coldStatistics.setEdge_d_abs_lenAll(edge_d_abs_lenAll);
            coldStatistics.setEdge_e_abs_lenAll(edge_e_abs_lenAll);

            return ResultData.ResultDataSuccess(list, count, coldStatistics);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("查询失败,失败信息为" + e.getMessage(), null);
        }
    }


    public ResultData findLineDataByVolumeNo(JSONObject json) {
        JSONArray jsonArray = json.getJSONArray("volumeNos");
        List<String> volumeNo = jsonArray.toJavaList(String.class);
        if (CollectionUtils.isEmpty(volumeNo)) {
            return ResultData.ResultDataFaultSelf(null, "传入卷号为空");
        }

        Map<String, Map<String, Object>> map = new HashMap<>();
        Query query1 = new Query(Criteria.where("extid").in(volumeNo));
        List<JDataSave621> list = mongoTemplate.find(query1, JDataSave621.class);

        for (JDataSave621 jDataSave621 : list) {
            Map<String, Object> mapValue = new HashMap<>();
//            Query query=new Query(Criteria.where("extid").is(no));
//            JDataSave621 jDataSave621 = mongoTemplate.findOne(query, JDataSave621.class);
            Object list1 = jDataSave621.getRow().get("c621_tcm_ens1_tension_act");
            Object list2 = jDataSave621.getRow().get("c621_tcm_s1s2_tension_act");
            Object list3 = jDataSave621.getRow().get("c621_tcm_s2s3_tension_act");
            Object list4 = jDataSave621.getRow().get("c621_tcm_s3s4_tension_act");
            Object list5 = jDataSave621.getRow().get("c621_tcm_exs4_tension_act");
            Object list6 = jDataSave621.getRow().get("c621_tcm_s1_force_act");
            Object list7 = jDataSave621.getRow().get("c621_tcm_s2_force_act");
            Object list8 = jDataSave621.getRow().get("c621_tcm_s3_force_act");
            Object list9 = jDataSave621.getRow().get("c621_tcm_s4_force_act");
            Object list10 = jDataSave621.getRow().get("c621_tcm_s1_wr_bendingforce_act");
            Object list11 = jDataSave621.getRow().get("c621_tcm_s2_wr_bendingforce_act");
            Object list12 = jDataSave621.getRow().get("c621_tcm_s3_wr_bendingforce_act");
            Object list13 = jDataSave621.getRow().get("c621_tcm_s4_wr_bendingforce_act");
            Object list14 = jDataSave621.getRow().get("c621_tcm_s1_up_mr_shifting_act");
            Object list15 = jDataSave621.getRow().get("c621_tcm_s2_up_mr_shifting_act");
            Object list16 = jDataSave621.getRow().get("c621_tcm_s3_up_mr_shifting_act");
            Object list17 = jDataSave621.getRow().get("c621_tcm_s4_up_mr_shifting_act");


            mapValue.put("c621_tcm_ens1_tension_act", list1);
            mapValue.put("c621_tcm_s1s2_tension_act", list2);
            mapValue.put("c621_tcm_s2s3_tension_act", list3);
            mapValue.put("c621_tcm_s3s4_tension_act", list4);
            mapValue.put("c621_tcm_exs4_tension_act", list5);

            mapValue.put("c621_tcm_s1_force_act", list6);
            mapValue.put("c621_tcm_s2_force_act", list7);
            mapValue.put("c621_tcm_s3_force_act", list8);
            mapValue.put("c621_tcm_s4_force_act", list9);

            mapValue.put("c621_tcm_s1_wr_bendingforce_act", list10);
            mapValue.put("c621_tcm_s2_wr_bendingforce_act", list11);
            mapValue.put("c621_tcm_s3_wr_bendingforce_act", list12);
            mapValue.put("c621_tcm_s4_wr_bendingforce_act", list13);

            mapValue.put("c621_tcm_s1_up_mr_shifting_act", list14);
            mapValue.put("c621_tcm_s2_up_mr_shifting_act", list15);
            mapValue.put("c621_tcm_s3_up_mr_shifting_act", list16);
            mapValue.put("c621_tcm_s4_up_mr_shifting_act", list17);

            String extid = jDataSave621.getExtid();
            if (StringUtils.hasText(extid)) {
                map.put(extid, mapValue);
            }
        }
        if (!CollectionUtils.isEmpty(map)) {
            return ResultData.ResultDataSuccess(map);
        }
        return ResultData.ResultDataFaultSelf(null, "查询数据为空");
    }


    /**
     * 列表导出功能
     * @param jsonObject
     * @param response
     */
    public void export(JSONObject jsonObject, HttpServletResponse response) {
        // 接收传入参数
        Integer pageSize = jsonObject.getInteger("pageSize");
        Integer pageCount = jsonObject.getInteger("pageCount");
        String fileNames = jsonObject.getString("fileName");
        JSONObject condition = jsonObject.getJSONObject("condition");
        //查询条件
        String cold_coil_id = null;
        String hot_id = null; // 热卷号
        String dbegin = null;
        String dend = null;
        String ex_thk1 = null;  //产品厚度----开始
        String ex_thk2 = null;  //产品厚度---结束
        String en_wid1 = null;  //原料宽度----开始
        String en_wid2 = null;  //原料宽度----结束
        String en_thk1 = null;  //原料厚度----开始
        String en_thk2 = null;  //原料厚度----结束
        String ele_si1 = null;  //硅含量---开始
        String ele_si2 = null;  //硅含量---结束
        String steelgrade = null;  //钢种
        String shift = null;
        String crew = null;
        if (!condition.isEmpty()) {
            if (StringUtils.hasText(condition.getString("cold_coil_id"))) {
                cold_coil_id = condition.getString("cold_coil_id");
            }
            if (StringUtils.hasText(condition.getString("hot_id"))) {
                hot_id = condition.getString("hot_id");
            }
            if (StringUtils.hasText(condition.getString("dbegin"))) {
                dbegin = condition.getString("dbegin");
            }
            if (StringUtils.hasText(condition.getString("dend"))) {
                dend = condition.getString("dend");
            }
            if (StringUtils.hasText(condition.getString("ex_thk1"))) {
                ex_thk1 = condition.getString("ex_thk1");
            }
            if (StringUtils.hasText(condition.getString("ex_thk2"))) {
                ex_thk2 = condition.getString("ex_thk2");
            }
            if (StringUtils.hasText(condition.getString("en_wid1"))) {
                en_wid1 = condition.getString("en_wid1");
            }
            if (StringUtils.hasText(condition.getString("en_wid2"))) {
                en_wid2 = condition.getString("en_wid2");
            }
            if (StringUtils.hasText(condition.getString("en_thk1"))) {
                en_thk1 = condition.getString("en_thk1");
            }
            if (StringUtils.hasText(condition.getString("en_thk2"))) {
                en_thk2 = condition.getString("en_thk2");
            }
            if (StringUtils.hasText(condition.getString("ele_si1"))) {
                ele_si1 = condition.getString("ele_si1");
            }
            if (StringUtils.hasText(condition.getString("ele_si2"))) {
                ele_si2 = condition.getString("ele_si2");
            }
            if (StringUtils.hasText(condition.getString("steelgrade"))) {
                steelgrade = condition.getString("steelgrade");
            }
            if (StringUtils.hasText(condition.getString("shift"))) {
                shift = condition.getString("shift");
            }
            if (StringUtils.hasText(condition.getString("crew"))) {
                crew = condition.getString("crew");
            }




            // 调用service查询出数据
            List<ColdEdgeSame> data = null;
            List<ExportColdEdgeSame> list = new ArrayList<>();
            for (int i = 1; i <= pageCount; i++) {
                // 分页去数据库查询数据 这里可以去数据库查询每一页的数据
                data = coldEdgeSameDao.findDataByPage((i - 1) * pageSize, i * pageSize, dbegin, dend, ex_thk1, ex_thk2, en_wid1, en_wid2, en_thk1, en_thk2, ele_si1, ele_si2, steelgrade, shift, crew, cold_coil_id,hot_id);
                if (!data.isEmpty() && data.size() > 0) {
                    for (ColdEdgeSame item : data) {
                        ExportColdEdgeSame exportColdEdgeSame = new ExportColdEdgeSame();
                        BeanUtils.copyProperties(item,exportColdEdgeSame);
                        list.add(exportColdEdgeSame);
                    }
                }
            }
            try {
                Map<String,Object> data1 = new HashMap();
                data1.put("data",list);
                File file = ResourceUtils.getFile("classpath:exceltemplate\\冷轧工艺边降分析.xlsx");
                TemplateExportParams templateExportParams = new TemplateExportParams(file.getPath(),false);
                templateExportParams.setDictHandler(new PlanExcelHandlerImpl());
                Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, data1);
                ExcelUtilsPOI.exportExcel(fileNames,response,workbook);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
